/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.soa.controller.wx;

import com.lianzt.commondata.AbstractCommonData;
import com.lianzt.commondata.DataConvertFactory;
import com.lianzt.exception.InstanceDataException;
import com.lianzt.util.HttpConnect;
import com.lianzt.util.StringUtil;
import com.soa.exception.GlobalException;
import com.soa.service.BaseService;
import static com.soa.service.BaseService.getSession;
import com.soa.service.impl.UtilService;
import com.soa.util.AjaxUtil;
import com.soa.util.SystemUtil;
import com.soa.util.wx.SHA1;
import com.soa.util.wx.WeixinUtil;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;
import java.util.logging.Level;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 微信相关控制器
 *
 * @author zuotai
 */
@Controller
public class InterfaceController {
    
    @Resource
    private UtilService utilServiceImpl;
    @Resource
    private WeixinUtil weixinUtil;
    private final Logger log = LoggerFactory.getLogger(InterfaceController.class);
    private final String WX_ERROR_VIEW = "/wx_error";
    private final String TOKEN_URL = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=%s&secret=%s&code=%s&grant_type=authorization_code";

    /**
     * 其它微信平台接入的地址，get或post中包含了appid、sign、uid、lxdh、hphm、dabh。进入地址后需跳转到oauth2.0授权页面，获取用户在快撤快赔系统中的openid，并转到主页
     *
     * @param request
     */
    /**
     * 对外提供的接口
     *
     * @param request
     * @param out
     * @param user_id 用户id
     * @param service_id 服务码
     */
    @RequestMapping(value = "/interfaceTccgl", method = RequestMethod.POST)
    public void welcome(HttpServletRequest request, PrintWriter out) throws IOException {
     
       log.info("接口获取到的request数据为{}"+request+"-----");
        String string = "";
        int contentLength = request.getContentLength();
         InputStream in = null;
          try {
                in = request.getInputStream();
                byte[] bt = new byte[1024];
                int i = 0, totle = 0;
                while (totle < contentLength) {
                    i = in.read(bt);
                  string =string+new String(bt, 0, i, "utf-8");
                    totle += i;
                }
            } finally {
                try {
                    in.close();
                } catch (IOException ex1) {
                    log.error("关闭数据流错误", ex1);
                }
            }
           
       log.info("接口获取到的数据为{}"+string+"-----");
        
        AbstractCommonData req = null;
         AbstractCommonData wxData = null;
            AbstractCommonData res = null; //响应报文
            AbstractCommonData resHead = null; 
            AbstractCommonData reqHead = null;
        try {
           
            wxData = DataConvertFactory.getInstanceByJson(string);
            req = (AbstractCommonData) request.getAttribute("page_data");
            req.putAll(wxData);
            reqHead = req.getDataValue("head");
            reqHead.putStringValue("service_code",wxData.getStringValue("serviceCode"));
            reqHead.putDateValue("send_time", new Date());
            res = DataConvertFactory.getInstance();     //响应报文
            resHead = res.getDataValue("head");
        
        } catch (InstanceDataException ex) {
            java.util.logging.Logger.getLogger(InterfaceController.class.getName()).log(Level.SEVERE, null, ex);
        }
    
        AbstractCommonData data;
        if (checkReq(request)) {

            String outJson = DataConvertFactory.praseNormJson(req);
            log.info("---------用户报文---------：{}", req);
            try{
            BaseService.runService(req, reqHead, res, resHead);
            }
            catch(Exception e){
            log.error(e.toString());
            res.putStringValue("restate", "-1");
            res.putStringValue("redes", "发送失败请联系管理员");
            }log.info("----------controller返回数据---------：{}", res);
            res.remove("head");
            String dataJson = DataConvertFactory.praseNormJson(res);
            out.print(dataJson);
        } else {
            data = DataConvertFactory.getInstanceEmpty();
            data.putStringValue("restate", "-1");
            data.putStringValue("redes", "IP地址有误");
            out.print(DataConvertFactory.praseNormJson(data));
        }
    }

    /**
     * 校验IP是否合法
     *
     * @param req
     * @param user
     * @param serviceId
     */
    private boolean checkReq(HttpServletRequest req) {
        //校验IP地址
            return true;
    }
}
